#include "hal_flash.h"
//typedef enum {FAILED = 0, PASSED = !FAILED} TestStatus;

void hal_flash_write(void *flash_addr, void *src_buf, uint16 len)
{
	u32 g_sun = 0x00000000;
	u32 Address = 0x00;
	u8 num = 0;
	signed char i,j;
	Address = (uint32_t)flash_addr;
	uint8 *str = (uint8 *)src_buf;
	
  FLASH_Unlock();
	FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR);
	if(FLASH_ErasePage((uint32_t)flash_addr)!= FLASH_COMPLETE)
  {
		while (1)
    {
    }
  }

	for(j=len/4;j>=0;j--)
	{
		g_sun = 0;
		if(j==0)
		{
			num = len%4;
			switch(num)
			{
				case 1:
				case 2:
				case 3:		
				for(i=num-1 ;i >=0 ;i--)
				{
					g_sun |= str[i];
					if(i > 1)
					{
						g_sun = (g_sun << 8);
					}
					else
					{
						g_sun = (g_sun << 8*i);
					}
				}		
					break;
			}
		}
		else 
		{
				for(i = 3; i >= 1; i--)
				{
					g_sun |= str[i];
					g_sun = (g_sun << 8); 
				}		
				g_sun |= str[0];
		}
		str =str+4;
    if (FLASH_ProgramWord(Address, g_sun) == FLASH_COMPLETE)
    {
      Address = Address + 4;
    }
    else
    { 
    }
  }
	
	FLASH_Lock();
}
